package com.crm.common.util;

import com.crm.common.constant.ProjectBusinessConstant;
import com.sun.mail.util.MailSSLSocketFactory;
import lombok.extern.slf4j.Slf4j;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;


/**
 * @Author:chaifuyou
 * @Date: 2021/6/10 14:25
 */
@Slf4j
public class SendEamil {
    public static void sendEamil(String sendTitle,String sendText,String sendEamil) {
        try {
            //创建一个配置文件并保存
            Properties properties = new Properties();

            properties.put("mail.smtp.host",ProjectBusinessConstant.EMAIL_SERVICE_PATH);

            properties.put("mail.transport.protocol","smtp");

            properties.put("mail.smtp.auth","true");
            properties.put("mail.smtp.port", "465");


            //QQ存在一个特性设置SSL加密
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);

            //创建一个session对象
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(ProjectBusinessConstant.EMAIL_SEND_ACCOUNT, ProjectBusinessConstant.EMAIL_SEND_PASSWORD);
                }
            });

            //开启debug模式
            session.setDebug(true);

            //获取连接对象
            Transport transport = session.getTransport();

            //连接服务器
            transport.connect(ProjectBusinessConstant.EMAIL_SERVICE_PATH,ProjectBusinessConstant.EMAIL_SEND_ACCOUNT,
                    ProjectBusinessConstant.EMAIL_SEND_PASSWORD);

            //创建邮件对象
            MimeMessage mimeMessage = new MimeMessage(session);

            //邮件发送人
            mimeMessage.setFrom(new InternetAddress(ProjectBusinessConstant.EMAIL_SEND_ACCOUNT));

            //邮件接收人
            mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(sendEamil));

            //邮件标题
            mimeMessage.setSubject(sendTitle);

            //邮件内容
            mimeMessage.setContent(sendText,"text/html;charset=UTF-8");

            //发送邮件
            transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());

            //关闭连接
            transport.close();
        } catch (Exception e) {
            log.error("发送邮件异常： "+e);
        }
    }

}
